<?php

#	Fastfoo - CMS developer under CakePHP / http://fast-foo.com
#	Copyright (C) 2010  Antonio Irlandés García

#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.

#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.

#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

class PagesController extends AppController{
	
	/*****************
	** Variables Generales
	*****************/
	public $name = 'Pages';//nombre controlador
	public $uses = array('Page', 'Permission', 'Aro', 'Aco');//modelos empleados
	public $helpers = array('Tinymce');//helpers empleados
	public $components = array('Urlfriendly');//componentes empleados
	public $layout = 'main';//disposición de diseño por defecto

	/*****************
	** Variables Administracion
	*****************/
	public $search_form = true;//mostramos el buscador si o no
	public $cmp_search = 'Page.title';//campo de la BD que emplearemos para la BD (filtrar en las busquedas)
	public $sub_menu = array("pages" => "index");//Subsecciones en submenu
	public $action_menu = array("list_pages" => "index","add_page"=>"view");//Acciones del menu accion
	public $lnregpp = array(20,40,60,80,100);//Numero de registros mostrados por pagina

	/*****************
	** Respuestas de controlador a una accion
	*****************/
	public $result_action;//Resultado de la operaciones
	public $msg_result;//Mensaje de la operacion

	/**
	 * Muestra la pagina indicada
	 *
	 * @param string $title indica el title_url de la pagina
	 * @return void
	 */
	public function view($title_url = null){

	 	$this->layout = 'main';

		if(!empty($title_url)){

			$data_page = $this->Page->find('first',array('conditions' => array('Page.public' => '1', 'Page.title_url' => $title_url)));
			
			if(!empty($data_page) && $data_page['Page']['public'] == 1){

				//Comprobamos si se posee permiso para acceder a dicha pagina
				if(!$this->_checkPermissions(array('title_url' => $data_page['Page']['title_url']))){
					$this->Session->setFlash($this->Auth->authError, 'default', array('class' => 'info_sys_error'));
					$this->redirect($this->referer());
				}
				

				$this->set('data_page',$data_page);
			    //Titulo de la pagina
			    $this->set('title_for_layout', $this->config_general['title_web']." - ".$data_page['Page']['title_url']);
			}else{
				#Vista a renderizar
   				$this->cakeError('error404', array('url' => $title_url));
			}

		}else{
				#Vista a renderizar
				$this->cakeError('error404', array('url' => $title_url));
		}
	}

////////////////////////////////////////////////////////////////////////////
//////*ESTOS METODOS DEBEN ESTAR LIMITADOS A LOS ADMINISTRADORES*//////////
//////////////////////////////////////////////////////////////////////////


	/*********************
	**
	** Obtiene un listado de los registros - Panel administracion
	**
	*********************/

	public function admin_index(){

 		$this->layout = 'admin';

		//numero de registros a mostrar
		if(isset($this->params['named']['nreg']) && in_array($this->params['named']['nreg'],$this->lnregpp)){
			$i_array = array_keys($this->lnregpp,$this->params['named']['nreg']);
			$nreg = $this->lnregpp[$i_array[0]];
		}else{
			$nreg = $this->lnregpp[0];
		}
		
		//palabra a buscar
		(isset($this->params['named']['search'])) ? $search = $this->params['named']['search'] : $search = null;
		//pagina
		(isset($this->params['named']['page'])) ? $page = $this->params['named']['page'] : $page = 1;

		//Parametros que paso al paginador
		$this->paginate = array('limit' => $nreg,
								'order' => null,
								'conditions' => $this->cmp_search." LIKE '%".$search."%'",
								'recursive' => 2);

		//obtengo todos los registros y setemos
		$this->set('registers', $this->paginate('Page'));
		
		//menu derecho
		$this->set('action_menu', $this->action_menu);

		//submenu
		$this->set('sub_menu', $this->sub_menu);

		//Mostramos el buscador
		$this->set('search_form', $this->search_form);	

		//palabra buscada
		$this->set('search', $search);

		//lista de valores para mostrar por pantalla
		$this->set('lnregpp', $this->lnregpp);

		//pagina donde me encuentro
		$this->set('page', $page);

		//Valor elegido en la lista de valores
		$this->set('nreg', $nreg);

	}


	/*********************
	**
	** Muestra registro - Panel administracion
	**
	*********************/
	public function admin_view($id = null){

 		$this->layout = 'admin';

		//Seteo las secciones del menu izquierdo
		$this->set('action_menu', $this->action_menu);

		//Seteo las secciones del submenu
		$this->set('sub_menu', $this->sub_menu);

		//Mostramos el buscador
		$this->set('search_form', $this->search_form);	

		//Datos del registro
		$this->Page->id = $id;
        $this->set('register', $this->Page->read());
	}


	/*********************
	**
	** Añade registro - Panel administracion
	**
	*********************/
	public function admin_add(){

 		$this->autoRender = false;
		
		if(!empty($this->data) && $this->RequestHandler->isAjax()){

			//Created
			if(empty($this->data['Page']['id']))
				$this->data['Page']['created'] = date("Y-m-d H:i:s"); 

			//Modified
			if(!empty($this->data['Page']['id']))
				$this->data['Page']['modified'] = date("Y-m-d H:i:s"); 


			//Transformamos el titulo a una url amigable
			$this->data['Page']['title_url'] = $this->Urlfriendly->parseUrl($this->data['Page']['title']);

		
			//Aseguro la entrada de datos con sanitize
			$this->data = Sanitize::clean($this->data,
										  array('odd_spaces' => true,
												'encode' => false,
												'dollar' => true,
												'carriage' => true,
												'unicode' => true,
												'escape' => false,
												'backslash' => true));
		
		
			//Validamos la entrada de datos
			if ($this->Page->create($this->data) && $this->Page->validates()){
				//Salvamos los datos en la BD
				if ($this->Page->save($this->data)){

				//Si se trata de una nueva inserccion actualizamos el campos ID en el formulario
				if(empty($this->data['Page']['id'])){
					$name_reg = $this->Page->name."Id";
					$value_reg = $this->Page->lastReg();
				}


					####INICIO LOG del sistema
					if(isset($this->data['Page']['id']) && !empty($this->data['Page']['id'])){
						$id_reg = $this->data['Page']['id'];
						$action_reg = "update_page";

					}else{
						$id_reg = $this->Page->lastReg();
						$action_reg = "add_page";
					}

					$data_log = array ( "title" => "'".$this->data['Page']['title']."' (".__($action_reg, true).")",
										"section" => $this->name,
										"url" => Router::url(array('admin' => true,'controller'=> strtolower($this->name), 'action'=>'view', $id_reg), true),
										"created" => date("Y-m-d H:i:s")
										);

					$this->Log->addRegister($data_log);
					####FIN LOG


					#####AÑADO A LAS ACL
					$this->_insertAcl($id_reg);
					#####FIN ACL

					//Mensaje a lanzar
					$this->result_action = true;
					$this->msg_result = "data_saved_correctly";
			
				}else{
					$this->result_action = false;
					$this->msg_result = "error_saving";
				}

			}else{
				//Errores
				$this->result_action = false;
				$this->msg_result = array_shift($this->validateErrors($this->Page));
			}

		}else{
			$this->result_action = false;
			$this->msg_result = "form_must_fill";
		}			

		//Si hemos pulsado en publico redirigira al listado
		if($this->data['Page']['public'] == 1){
			$url_redirect = Router::url(array('admin' => true,'action'=>'index'), true)."#result_system";
			//Para cuando se redirija mediante javascript siga mostrando el mensaje
			$this->Session->setFlash(__($this->msg_result, true), 'default', array('class' => $this->msg_class));
		}else{
			$url_redirect = null;
		}

		//Devuelvo datos del mensaje e identificador (array --> json)
		echo (json_encode(array("result_action" => $this->result_action,
								"msg_result" => __($this->msg_result, true),
								"name_reg" => $name_reg,
								"value_reg" => $value_reg,
								"url_redirect" => $url_redirect
								)
						)
			);
	}



	/*********************
	**
	** Elimina los registros - Panel administracion
	**
	*********************/
	public function admin_delete(){

		if(isset($this->params['form']['list_reg'])){

			if(count($this->params['form']['list_reg']) != 0){

				for($i = 0; $i < count($this->params['form']['list_reg']); $i++){

					if($this->params['form']['list_reg'][$i] != ""){

						####INICIO LOG del sistema
						$this->Page->id = $this->params['form']['list_reg'][$i];
						$data_register = $this->Page->read();

						//datos que se almacenarán en el LOG del sistema y la actividad de session del usuario
						$data_log = array ( "title" => "'".$data_register['Page']['title']."' (".__('deleted', true).")",
											"section" => $this->name,
											"url" => null,
											"created" => date("Y-m-d H:i:s")
											);

						$this->Log->addRegister($data_log);

						####FIN LOG

						//Borramos su referencia en las listas ACL
						$this->_delAcl($this->params['form']['list_reg'][$i]);

						///borramos pagina
						$this->Page->delete($this->params['form']['list_reg'][$i]);
			

						//datos a devolver
						$this->msg_result = "del_registers_correctly";

					}else{
						//datos a devolver
						$this->msg_result = "error_process_delete";
					}
				}

			}else{
				//datos a devolver
				$this->msg_result = "select_one_register";
			}
				
		}else{
			//datos a devolver
			$this->msg_result = "no_operations";
		}

		//Mensaje que devuelve
		$this->Session->setFlash(__($this->msg_result, true), 'default');
		//Redireccion 
		$this->redirect($this->referer()."#result_system");
	}	



	/*********************
	**
	** Cambia el estado publico de los elementos - Panel administracion
	**
	*********************/
 	public function admin_setPublic(){
 	
 		$this->autoRender = false;
 		$this->layout = null;
 		 
		if($this->RequestHandler->isAjax()){
 			$this->Page->setPublic($this->params['form']['id'],$this->params['form']['estate']);

			####INICIO LOG del sistema
			if($this->params['form']['estate'] == '0' || $this->params['form']['estate'] == null){
				$action_reg = "no_published";
			}else{
				$action_reg = "published";
			}

			$this->Page->id = $this->params['form']['id'];
			$data_register = $this->Page->read();

			$data_log = array ( "title" => "'".$data_register['Page']['title']."' (".__($action_reg, true).")",
								"section" => $this->name,
								"url" => Router::url(array('admin' => true,'controller'=> strtolower($this->name), 'action'=>'view',$this->params['form']['id']), true),
								"created" => date("Y-m-d H:i:s")
								);

			$this->Log->addRegister($data_log);
			####FIN LOG

 		}else{
			//Redireccion
			$this->redirect($this->referer());
 		}
 	}

	/**
	 * Inserta la nueva página en las tabla ACL para poder ser tratada con sus permisos pertinentes
	 *
	 * @param integer $id indica el identificador del registro a insertar
	 * @return void
	 */
    private function _insertAcl($id){

		$this->autoRender = false;

		if(!empty($id)){

			//Obtengo datos del hijo que deseo insertar
			$this->Page->id = $id;
			$data_register = $this->Page->read();

			if(empty($data_register)){
				return false;
			}

			$aco =& $this->Acl->Aco;

			//Si el nodo no existe
			if($aco->find("count", array("conditions" => "alias = 'pagecreated-".$data_register['Page']['title_url']."'")) == 0 ){
				//Busco el padre todas las paginas(nodo padre)
				$controllerNode = $aco->node('controllers/'.$this->name.'/view');//Este es su padre natural, el metodo "view"
				//Genero el nuevo nodo
				$aco->create(array('parent_id' => $controllerNode['0']['Aco']['id'], 'model' => null, 'alias' => 'pagecreated-'.$data_register['Page']['title_url']));
				//Lo salvo
				$aco->save();
				
				return true;
			}

		}else{
			return false;
		}

	}

	/**
	 * Elimina la paǵina de las listas ACL
	 *
	 * @param integer $id indica el identificador del registro a insertar
	 * @return void
	 */
    private function _delAcl($id){

		$this->autoRender = false;

		if(!empty($id)){

			//Obtengo datos del hijo que deseo borrar
			$this->Page->id = $id;
			$data_register = $this->Page->read();

			if(empty($data_register)){
				return false;
			}

			$aco =& $this->Acl->Aco;

			//Eliminamos referencia en ACL
			if($aco->deleteAll("alias = 'pagecreated-".$data_register['Page']['title_url']."'", true)){	
				return true;
			}else{
				return false;
			}

		}else{
			return false;
		}

	}



	/**
	 * Verifica los permisos del usuario frente a la peticion
	 *
	 * @param array $array_data array que comprende el metodo o accion y la lista de variables pasadas
	 * @return void
	 */
	private function _checkPermissions($array_data){

		//Antes de nada vemos el estado de los permisos generales
		if($this->Auth->allowedActions[0] == '*')
			return true;

		if(!is_array($array_data))
			return false;

		//Extrae las variables del array enviado
		extract($array_data);

		//Obtengo las variables de session del usuario
		$data_user = $this->Session->read('Auth.User');

		//ACO de la pagina 
		$aco_page = $this->Aco->find("first",array("conditions" => "alias = 'pagecreated-".$title_url."'", "recursive" => "-1"));

		//ARO del grupo 
		$aro_group = $this->Aro->find("first",array("conditions" => "foreign_key = '".$data_user['group_id']."' AND model = 'Group'", "recursive" => "-1"));

		//ARO del user 
		$aro_user = $this->Aro->find("first",array("conditions" => "foreign_key = '".$data_user['id']."' AND model = 'User'", "recursive" => "-1"));

		//ARO del grupo 
		$aro_group = $this->Aro->find("first",array("conditions" => "foreign_key = '".$data_user['group_id']."' AND model = 'Group'", "recursive" => "-1"));


		//Permisos del grupo sobre la página
		if($this->Permission->find("count", array("conditions" => "aro_id = '".$aro_group['Aro']['id']."' AND aco_id = '".$aco_page['Aco']['id']."' AND _read = '1'", "recursive" => "-1")) > 0){
			return true;

		}

		//Permisos del grupo sobre la página
		if($this->Permission->find("count", array("conditions" => "aro_id = '".$aro_user['Aro']['id']."' AND aco_id = '".$aco_page['Aco']['id']."' AND _read = '1'", "recursive" => "-1")) > 0)
			return true;

		return false;
		
	}

}
?>
